package cn.dceast.config;

import cn.dceast.common.AccessLevel;
import cn.dceast.common.AccessPolicy;
import cn.dceast.common.UserLevel;
import cn.dceast.common.data.Constants;
import cn.dceast.common.data.RtnData;
import cn.dceast.common.utils.FrameUtil;
import cn.dceast.user.model.UserInfo;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Map;

/**
 *
 *用户登录验证过滤器
 */
@Component
public class AccessPolicyInterceptor extends HandlerInterceptorAdapter {
	private static Logger logger = Logger.getLogger(AccessPolicyInterceptor.class);
	private static Gson gson = new Gson();
	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		AccessPolicy accessPolicy = (AccessPolicy) method
				.getAnnotation(AccessPolicy.class);
		if (accessPolicy == null) {
			accessPolicy = (AccessPolicy)handlerMethod.getClass().getAnnotation(AccessPolicy.class);
		}
		//1、检测该接口是否对外开放
		if(accessPolicy == null) {
			return true;
		} else if (accessPolicy.accessLevel() == AccessLevel.PROTECTED) {
			FrameUtil.responseJson(gson.toJson(request), response);
			logger.error("============AccessPolicyInterceptor:无权限访问==============");
			return false;
		}
		//2、检测该接口所需要的权限
		if (accessPolicy.userLevel() == UserLevel.PUBLIC) {
			return true;
		}
		//3、剩余的都需要进行用户信息的获取并验证
		UserInfo userInfo = null;
		HttpSession session = request.getSession(false);
		if(session != null){
			userInfo =  (UserInfo)session.getAttribute("userInfo");
		}
		//UserInfoEntity
		ResponseBody requestBody = (ResponseBody)method.getAnnotation(ResponseBody.class);
		boolean isJsonRequest = requestBody != null ? true:false;
		if (null == userInfo) {
			logger.error("============AccessPolicyInterceptor:请登录后再进行访问==============");
			if (isJsonRequest) {
				FrameUtil.responseJson(gson.toJson(RtnData.fail(null, Constants.NEED_LOGIN_CODE,Constants.NEED_LOGIN_MSG)), response);
			} else {
				response.sendRedirect("/user/login.html?" + Constants.CALL_BACK + "="+geURLAndtRequestParam(request));
			}

			System.out.println(request.getRequestURL());
			return false;
		}
		return true;
	}

	/**
	 *获取访问请求的路径
	 * @param req
	 * @return
     */
	private String geURLAndtRequestParam(HttpServletRequest req) {

		Map<String, String[]> params = req.getParameterMap();
		String queryString = "";
		for (String key : params.keySet()) {
			String[] values = params.get(key);
			for (int i = 0; i < values.length; i++) {
				String value = values[i];
				queryString += key + "=" + value + "&";
			}
		}
		// 去掉最后一个空格
		String url = req.getRequestURL().toString();
		if (!StringUtils.isEmpty(queryString)) {
			queryString =  queryString.substring(0, queryString.length() - 1);
			url = url + "?"+queryString;
		}
		try {
			 url = URLEncoder.encode(req.getRequestURL()+"?"+queryString,"UTF-8");
			return url;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.error("进行回调地址编码时发生异常",e);
		}
		return url;
	}
}
